package com.gmrz.uaf.servlet.v1.servlet;

import com.gmrz.uaf.servlet.v1.handler.UAFAuthResponseHandler;
import com.gmrz.util.Convert;
import com.gmrz.util.Strings;
import com.gmrz.webauthn.handler.WebAuthResponseHandler;
import com.google.inject.Singleton;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * Created by gmrz-ops on 2017/7/12.
 */
@Singleton
public class UAFAuthResponseServlet extends HttpServlet {
    private static final Logger LOG = LogManager.getLogger(UAFAuthResponseServlet.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        ServletInputStream inputStream = req.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int lens = -1;
        while ((lens = inputStream.read(b)) > 0) {
            content.write(b, 0, lens);
        }
        String request = content.toString("UTF-8");// 内容
        String transNo = Convert.getTransNoFromContext(request);
        ThreadContext.put("transNo", transNo);

        String response = "";
        Map<String, Object> paramsMap = Convert.getInfoFromRequest(request);

        if ((paramsMap.get("protocol") != null) && (Strings.equals((String) paramsMap.get("protocol"), "web"))) {
            WebAuthResponseHandler uafAuthResponseHandler = new WebAuthResponseHandler();
            response = uafAuthResponseHandler.authFinish(request);
        } else {
            UAFAuthResponseHandler uafAuthResponseHandler = new UAFAuthResponseHandler();
            response = uafAuthResponseHandler.authFinish(request);
        }

        resp.getWriter().write(response);
    }
}
